﻿// =============================================
// Author:		Oğuz Kurumlu
// Create date: <Create Date,,>
// Description:	<Description,,>
// =============================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Bosphorus.Migrator.Core.MigrationCommand;
using Bosphorus.Migrator.Core.MigrationFounder;
using Bosphorus.Migrator.Core;
using Bosphorus.Migrator.Implementation.MigrationCommand;

namespace Bosphorus.Migrator.Facade
{
    public static class MigratorFacade
    {

        //Oğuz
        //The man who write the amele kod :) 
        public static void Migrate(IList<IMigration> migrationList, int fromVersion, int toVersion)
        {
            int startNumber = fromVersion;
            int endNumber = toVersion;
            if (fromVersion > toVersion)
            {
                startNumber = toVersion;
                endNumber = fromVersion;
            }

            migrationList = migrationList.OrderBy(x => x.Version).ToList();

            IList<ICommand> commands = new List<ICommand>();
            foreach (IMigration migration in migrationList)
            {
                ICommand command;
                if (startNumber >= migration.Version)
                {
                    continue;
                }

                if (endNumber < migration.Version)
                {
                    //todo: what if migration versions comes disordered !
                    break;
                }

                if (fromVersion > toVersion)
                {
                    command = migration.Down();
                }
                else
                {
                    command = migration.Up();
                }
                commands.Add(command);
            }

            CommandFacade.Execute(commands);
        }

        public static void Migrate(IList<IMigration> migrationList, int toVersion)
        {
            Migrate(migrationList, 1, toVersion);
        }
    }
}
